package com.zeekr.orm.aop;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 吴文杰
 * @version 1.0
 * @since 2024/11/17 03:26
 */
@Aspect
// @Component
@Slf4j
public class LoginInterceptor {
  @Around("execution(* com.zeekr.orm.controller.*.*(..))")
  public Object doInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request =
            ((ServletRequestAttributes) requestAttributes).getRequest();
    String requestURI = request.getRequestURI();
    String requestId = UUID.randomUUID().toString();

    Object[] args = joinPoint.getArgs();
    String reqArgs = "["+ StringUtils.join(args, ",") +"]";

    log.info("request start, id:{}, path:{}, ip:{}, params:{}", requestId, requestURI, request.getRemoteHost(),reqArgs);

    Object proceed = joinPoint.proceed();
    stopWatch.stop();
    long time = stopWatch.getTotalTimeMillis();
    log.info("request end, id : {} , time : {} ms", requestId, time);
    return proceed;
  }
}
